package com.zut.controller;
import com.zut.pojo.Result;
import com.zut.pojo.User;
import com.zut.service.UserService;
import com.zut.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;
    @GetMapping("/login")
    public Result login(@RequestParam("tel") String tel, @RequestParam("password") String password){
        User user = new User();
        user.setPhone(tel);
//        String sPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(password);
        User u = userService.getUserByPhoneAndPassword(user);
        if (u != null){
            Map<String,Object> claims = new HashMap<>();
            claims.put("username",u.getUsername());
            claims.put("phone",u.getPhone());
            String s = JwtUtils.generateJwt(claims);
            ArrayList<String> list = new ArrayList<>();
            list.add(u.getUsername());
            list.add(s);
            return Result.success(list);
        }else {
            return Result.error("手机号或者密码错误");
        }
    }
    // 注册功能
    @PostMapping ("/register")
    public Result register(@RequestBody User user){
        //将页面提交的代码进行md5加密处理
//        String sPsw = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
//        user.setPassword(sPsw);
        int i = userService.register(user);
        if (i>0){
            return Result.success();
        }else {
            return Result.error("注册失败");
        }
    }

    // 检测手机号是否注册过功能
    @GetMapping ("/telTest")
    public Result telTest(String phone){
        User user = userService.telTest(phone);
        if (user==null){
            return Result.success();
        }else {
            return Result.error("手机号已注册过,请重新输入！！");
        }
    }
    // 认证功能
    @PostMapping("/authentication")
    public Result Authentication(@RequestBody User user){
        boolean i=userService.addAuthentication(user);
        if (i){
            return Result.success();
        }else {
            return Result.error("小子，你已经认证过了！！");
        }
    }

    // 发布人姓名、手机号、身份证号回显
    @GetMapping("/currentUser")
    public Result CurrentUser(HttpServletRequest req){
        String jwt = req.getHeader("Authorization");
        // 解析令牌
        String phone = (String) JwtUtils.parseJWT(jwt).get("phone");
        User user = userService.telTest(phone);
        return Result.success(user);
    }
}
